'''
@Company: TWL
@Author: xue jian
@Email: xuejian@kanzhun.com
@Date: 2020-06-26 17:05:30
'''
import fast

class Solution:
    def sort_2_media(self, nums):
        if len(nums)<=5:
            solution = fast.Solution()
            solution.sortArray(nums)
            # print('neibu', nums)
            nums[0], nums[len(nums)>>1] = nums[len(nums)>>1], nums[0] #寻找中位数并放在数组首位
            # print(nums)
            return 
        else:
            l = (len(nums)+4)//5
            for i in range(l):
                r = min(i*5+5, len(nums))
                tmp = nums[i*5:r]
                self.sort_2_media(tmp)
                nums[i*5:r] = tmp
                # print('waibu', nums[i*5: r])
                nums[i], nums[i*5] = nums[i*5], nums[i] #将中位数并放在数组前排
            # print('haha', nums)
            tmp = nums[:l]
            self.sort_2_media(nums[:l]) 
            nums[:l] = tmp
            

    def partition(self, nums):
        nums[0], nums[-1] = nums[-1], nums[0]
        target = nums[-1]
        i=0
        for j in range(len(nums)-1):
            if nums[j]< target:
                nums[i], nums[j] = nums[j], nums[i]
                i+=1
        # print(i)
        nums[i], nums[-1] = nums[-1], nums[i]
        return i, nums[i]

    def BFPRT(self, nums, k):
        self.sort_2_media(nums)
        # print(nums)
        i, v = self.partition(nums)
        # print(i, v)
        if i == k:
            return v
        elif i>k:
            # print(i, k)
            return self.BFPRT(nums[:i], k)
        else:
            # print(i, k)
            return self.BFPRT(nums[i:], k-i)

if __name__ == "__main__":
    solution = Solution()
    nums = [100, 1000, 1, 11, 111, 999, 898, 987, 352, 837, 73, 83, 28]
    k = 3
    t=solution.BFPRT(nums, k-1)
    print(t)
        